<template>
  <page-detail>
    <div class="form-container">
      <!-- 表单内容 -->
      <van-form ref="form">
        <van-field
          v-model="formData.courseName"
          label="课程名称"
          placeholder="请输入"
          :rules="[{ required: true, message: '请输入课程名称' }]"
        />

        <van-field
          v-model="formData.itemName"
          label="课程类型"
          placeholder="请选择"
          readonly
          clickable
          right-icon="arrow-down"
          @click="showTypePicker = true"
          :rules="[{ required: true, message: '请选择课程类型' }]"
        />
        <van-field
          v-model="formData.teacherName"
          label="教师姓名"
          placeholder="请输入"
          :rules="[{ required: true, message: '请输入教师姓名' }]"
        />
        <van-field
          v-model="formData.teacherPhone"
          label="教师联系方式"
          placeholder="请输入"
          :rules="[
            { required: true, message: '请输入联系方式' },
            { pattern, message: '请输入正确的联系方式' },
          ]"
        />
        <van-field
          v-model="formData.courseStartTimeName"
          label="课程开始时间"
          placeholder="请选择"
          readonly
          clickable
          @click="showTimeModal('courseStartTime')"
          :rules="[{ required: true, message: '请选择课程开始时间' }]"
        >
          <template #right-icon>
            <img
              src="../../static/image/rl-icon.png"
              style="width: 16px; height: 16px"
            />
          </template>
        </van-field>
        <van-field
          v-model="formData.courseEndTimeName"
          label="课程结束时间"
          placeholder="请选择"
          readonly
          clickable
          @click="showTimeModal('courseEndTime')"
          :rules="[{ required: true, message: '请选择课程结束时间' }]"
        >
          <template #right-icon>
            <img
              src="../../static/image/rl-icon.png"
              style="width: 16px; height: 16px"
            />
          </template>
        </van-field>
        <van-field
          v-model="formData.itemScore"
          label="课程分数"
          placeholder="请输入"
          :rules="[{ required: true, message: '请输入课程分数' }]"
        />
        <van-field
          v-model="formData.itemAddr"
          label="课程地点"
          placeholder="请选择"
          :rules="[{ required: true, message: '请选择课程地点' }]"
          readonly
          type="textarea"
          autosize
        >
          <template #button>
            <img
              src="@/static/select-map.png"
              style="width: 22px; height: 22px"
              @click="search"
            />
          </template>
        </van-field>
        <van-field
          v-model="formData.courseContent"
          label="课程安排"
          type="textarea"
          placeholder="请输入"
          autosize
        />
        <div class="upload-section">
          <div class="upload-title">宣传图</div>
          <ne-file-upload
            v-model="formData.itemPublicityUrls"
            :rules="[{ required: true, message: '请上传宣传图' }]"
          />
        </div>
      </van-form>

      <!-- 类型选择器 -->
      <van-popup v-model="showTypePicker" position="bottom">
        <van-picker
          show-toolbar
          :columns="typeList"
          @confirm="onTypeConfirm"
          @cancel="showTypePicker = false"
        />
      </van-popup>
      <van-popup
        v-model="showTime"
        position="bottom"
        :close-on-click-overlay="false"
      >
        <van-datetime-picker
          @confirm="dateConfirm"
          @cancel="showTime = false"
          v-if="timeType === 'courseStartTime'"
          v-model="formData.courseStartTime"
          type="datetime"
          title="开始时间"
          :min-date="minDate"
          :max-date="maxDate"
        />
        <van-datetime-picker
          @confirm="dateConfirm"
          @cancel="showTime = false"
          v-if="timeType === 'courseEndTime'"
          v-model="formData.courseEndTime"
          type="datetime"
          title="结束时间"
          :min-date="minDate"
          :max-date="maxDate"
        />
      </van-popup>
      <!--      <van-calendar v-model="showTime" :show-confirm="false" type="range" @confirm="dateConfirm" color="#66c2ff" :default-date="null"/>-->
    </div>
    <template #footer>
      <van-button round type="primary" style="width: 200px" @click="submit">
        立即发起
      </van-button>
    </template>
    <select-map ref="selectMap" @change="mapChange" />
  </page-detail>
</template>

<script>
import { Dialog, Toast } from 'vant'
import { getDict } from '../../api/tbDict'
import NeFileUpload from '../../components/NeFileUpload.vue'
import { mapGetters } from 'vuex'
import { tbCourseSave } from '../../api/tbCourse'
import SelectMap from '../../components/SelectMap.vue'
export default {
  name: 'wx_pages_zhfw_courseSubmit',
  components: { SelectMap, NeFileUpload },
  data() {
    return {
      timeType: '',
      minDate: new Date(2024, 0, 1),
      maxDate: new Date(2099, 10, 1),
      showTypePicker: false,
      showSubTypePicker: false,
      pattern: /^1[3-9]\d{9}$/,
      formData: {
        courseName: '',
        courseType: '',
        teacherName: '',
        teacherPhone: '',
        courseStartTime: new Date(),
        courseEndTime: new Date(),
        courseContent: '',
        coursePublicityUrl: '',
        courseStatus: '',
        itemScore: 0,
        approvalStatus: '',
        approvalContent: '',
        note: '',
        latitude: '',
        longitude: '',
      },
      typeList: [],
      subTypeList: [],
      // 上传的文件列表
      fileList: [],
      showTime: false,
    }
  },
  computed: {
    ...mapGetters(['userInfo']),
  },
  methods: {
    // 类型选择确认
    onTypeConfirm(value) {
      this.formData.courseType = value.value
      this.formData.itemName = value.text
      this.showTypePicker = false
    },
    // 提交表单
    submit() {
      const _this = this
      const formData = {
        ...this.formData,
        courseStartTime: this.$dayjs(this.formData.courseStartTime).format(
          'YYYY-MM-DD HH:mm:ss'
        ),
        courseEndTime: this.$dayjs(this.formData.courseEndTime).format(
          'YYYY-MM-DD HH:mm:ss'
        ),
      }
      formData.coursePublicityUrl =
        formData.itemPublicityUrls &&
        formData.itemPublicityUrls.map((i) => i.url).join(',')
      delete formData.itemPublicityUrls

      _this.$refs.form.validate().then(() => {
        // 验证宣传图是否上传
        if (!formData.coursePublicityUrl) {
          Toast('请上传宣传图')
          return
        }

        Dialog.confirm({
          title: '提示',
          message: '是否确认提交?',
        })
          .then(async () => {
            _this.$showLoading('提交中...')
            await tbCourseSave(formData)
            _this.$hideLoading()
            Toast.success({
              message: '提交成功',
              duration: 1500,
              onClose: () => {
                _this.$navigateBack()
              },
            })
          })
          .catch(() => {})
      })
    },
    dateConfirm(value) {
      this.showTime = false
      this.formData[this.timeType] = this.$dayjs(value).format(
        'YYYY-MM-DD HH:mm:ss'
      )
      this.formData[`${this.timeType}Name`] = this.$dayjs(value).format(
        'YYYY-MM-DD HH:mm:ss'
      )
    },
    showTimeModal(type) {
      this.showTime = true
      this.timeType = type
    },
    search() {
      this.$refs.selectMap.showModal()
    },
    mapChange(position) {
      this.formData.itemAddr = position.address
      this.formData.latitude = position.lat
      this.formData.longitude = position.lng
      this.formData = { ...this.formData }
    },
  },
  onLoad() {
    getDict('course_type').then((res) => {
      this.typeList = res.data.map((item) => ({
        text: item.dictValue,
        value: item.dictKey,
      }))
    })
  },
}
</script>

<style lang="scss" scoped>
.form-container {
  padding: 20px 16px;
  min-height: 100vh;
  background-color: #f7f8fa;

  .upload-section {
    margin: 20px 0;
    padding: 16px;
    background-color: #fff;
    border-radius: 8px;

    .upload-title {
      font-size: 14px;
      color: #333;
      margin-bottom: 16px;
    }

    .upload-btn {
      width: 80px;
      height: 80px;
      background-color: #f7f8fa;
      border-radius: 4px;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;

      .upload-text {
        font-size: 12px;
        color: #969799;
        margin-top: 8px;
      }
    }
  }
}
</style>
